<?php
/**
 * This file is part of the Agora distribution. 
 * Detailed copyright and licensing information can be found
 * in the gpl-3.0.txt file which should be included in the distribution.
 * 
 * @version		$Id: 3.0.14 Olympus 2010-09-28 rammstein4o $
 * @copyright  2007 - 2010 jVitals
 * @license   GPLv3 Open Source
 * @link       http://jvitals.com
 * @since      File available since initial release
 */
defined ('IN_AGORA') or die;

jimport('joomla.html.pane');

class View {
    var $smarty;
    var $template;
    var $doc;
    var $lang;
    var $root_url;
    var $timezone;
    var $tz_diff;

    function View($template = NULL) {
        $this->__construct($template);
    }

    function __construct($template = NULL) {
        ainclude('include|string');
        ainclude('include|smarty|Smarty.class');

        $this->template = $template;

		$this->smarty = new Smarty();
        
        $this->smarty->template_dir = AGORA_CURRENT_PATH . DS . 'template';
        $this->smarty->compile_dir = JPATH_ROOT.DS.'cache' . DS . 'com_agora';

        if (!is_dir($this->smarty->compile_dir)) {
            $_params = array('dir' => $this->smarty->compile_dir);
            require_once(SMARTY_CORE_DIR . 'core.create_dir_structure.php');
            smarty_core_create_dir_structure($_params, $this->smarty);
        }

        $this->smarty->cache_dir = JPATH_ROOT.DS.'cache' . DS . 'com_agora';
        $this->smarty->caching = false;
        if (defined('AGORA_HELP_TRANSLATE')) {
            $this->smarty->force_compile = true;
        }
        $this->smarty->compile_check = true;
        //			$this->smarty->error_reporting = E_ALL;

        $this->smarty->unregister_modifier('escape');
        $this->smarty->register_modifier('escape',array('AString', 'escape'));
        $this->smarty->register_modifier('translate',array('Agora', 'lang'));

        $this->smarty->register_modifier('agora_date',array(&$this, 'agoraDate'));

        $this->smarty->register_function('loadModule',array(&$this, 'loadModule'));
        $this->smarty->register_block('moduleExists',array(&$this, 'moduleExists'), false);

        $this->smarty->register_function('image',array('Agora', 'image'));
        $this->smarty->register_function('feed',array(&$this, 'agoraFeed'));
        $this->smarty->register_function('url',array(&$this, 'agoraURL'));
        $this->smarty->register_function('root_url',array(&$this, 'agoraRoot'));
        $this->smarty->register_function('style',array(&$this, 'agoraStyle'));
        $this->smarty->register_function('script',array(&$this, 'agoraScript'), false);
        $this->smarty->register_block('script_def',array(&$this, 'agoraScriptDef'), false);
        $this->smarty->register_block('once',array(&$this, 'once'), false);

        $this->smarty->register_prefilter(array(&$this, 'translate'));

        $this->doc = & JFactory::getDocument();
        $this->smarty->compile_id = Agora::getCurrentLanguage();

        $this->root_url = Agora::getRoot();
        $this->smarty->assign('root_url',AString::escape($this->root_url));
        $this->smarty->assign('self_url',AString::escape(Agora::getSelf()));
        $this->smarty->assign('site_url',AString::escape(Agora::getSite()));

        $my = & JFactory::getUser();
        $app = & JFactory::getApplication();
		
		// if user is logged in we use the user timezone, if guest - we use timezone in global settings
		$this->timezone = ((int)$my->guest ? $app->getCfg('offset') : $my->getParam('timezone',0));
		// the timestamp will already contain the server timezone difference so we have to subtract it
        $this->tz_diff = $this->timezone*3600 - date('Z');
		
        JHTML::_('behavior.mootools');
        JHTML::_('behavior.modal', 'a.modal');
        JHTML::_('behavior.tooltip');

        //$this->doc->addScript(Agora::getSite().'js/jquery-1.3.2.min.js');
        //$this->doc->addScriptDeclaration('$j=jQuery.noConflict();');
        
        // check for override in template
    
        $tmpl = JFactory::getApplication()->getTemplate();
		$templateCss = JPATH_ROOT . DS . 'templates' . DS . $tmpl . DS . 'css' . DS . 'com_agora.css';
		// see if the css file exists as a template override
		jimport('joomla.filesystem.file');
		if (JFile::exists($templateCss)) {
			$this->doc->addStyleSheet("templates/$tmpl/css/com_agora.css"); 
		}

        $this->smarty->register_block('pane',array(&$this,'pane'));
        $this->smarty->register_block('panel',array(&$this,'panel'));

        $this->pane = array();
		jimport('joomla.utilities.date');
		
    }

    function once($params,$content, & $smarty, $repeat) {
        if (!$content) return;

        static $already_done = array();

        $key = '_common_';

        if (isset($params['name'])) {
            $key = $params['name'];
        }

        if (isset($already_done[$key])) return;

        echo $content;
        $already_done[$key] = 1;
    }

    function assign($var, $value) {
        $this->smarty->assign($var,$value);
    }

    function assignRef($var, & $value) {
        $this->smarty->assign_by_ref($var,$value);
    }

    function pane($params, $content, & $smarty, &$repeat) {
        if (!$content) {
            if (!isset($params['name'])) {
                $smarty->trigger_error('parameter "name" is mandatory for {pane}');
                return;
            }
            $name = $params['name'];
            unset($params['name']);

            if (isset($params['type'])) {
                $type = $params['type'];
                unset($params['type']);
            } else {
                $type = 'Sliders';
            }

            $pane = & JPane::getInstance($type, $params);
            $this->pane[] = & $pane;

            echo $pane->startPane($name);
        } else {
            $pane = & array_pop($this->pane);
            if (!is_null($pane)) {
                echo $content;
                echo $pane->endPane();
            }
        }
    }

    function panel($params, $content, & $smarty, &$repeat) {
        if (count($this->pane) == 0) {
            $smarty->trigger_error('you need to use {pane} before {panel}');
            return;
        }

        $pane = & $this->pane[count($this->pane)-1];
        if (!$content) {
            echo $pane->startPanel(Agora::lang($params['lang']), $params['id']);
        } else {
            echo $content;
            echo $pane->endPanel();
        }
    }

    function moduleExists($params, $content, & $smarty, &$repeat) {
        if (!$content) return;
        if (!isset($params['name'])) {
            $smarty->trigger_error('parameter "name" is mandatory for loadModule()');
            return;
        }
        $position = $params['name'];
        $mods = & JModuleHelper::getModules($position);
        if (count($mods) > 0) {
            return $content;
        } else {
            return '';
        }
    }

    function loadModule($params,& $smarty) {
        if (Agora::getVar('format') === 'raw') return;
        //			return var_export($params,true);

        if (!isset($params['name'])) {
            $smarty->trigger_error('parameter "name" is mandatory for loadModule()');
            return;
        }
        $position = $params['name'];

        if (!isset($params['style'])) {
            $style = -3;
        } else {
            $style = $params['style'];
        }

        //			dump($params);die;

        $renderer   = $this->doc->loadRenderer('module');
        $params      = array('style'=>$style);

        $contents = '';
        foreach (JModuleHelper::getModules($position) as $mod)  {
            $contents .= $renderer->render($mod, $params);
        }

        return $contents;
    }

    function agoraDate($timestamp) {
		
        $d_format = $this->smarty->_tpl_vars['agora_config']['o_date_format'];
		$d_format = str_replace(array('M', 'F', 'D', 'l'), array('{\M}', '{\F}', '{\D}', '{\l}'), $d_format);
        $t_format = $this->smarty->_tpl_vars['agora_config']['o_time_format'];

        //if ($timestamp == '') {
        if (empty($timestamp)) {
			return Agora::lang('Never');
		}

        $now = AGORA_TIME + $this->tz_diff;
        $timestamp = ($timestamp - $server_timezone) + $this->tz_diff;
		
        $date = date($d_format, $timestamp);
		$date = $this->_intl($date, $timestamp);
        $time = date($t_format, $timestamp);

        $today = date($d_format, $now);
		$today = $this->_intl($today, $now);
        $yesterday = date($d_format, $now - 86400);
		$yesterday = $this->_intl($yesterday, $now - 86400);

        if ($date == $today) {
			$date = Agora::lang('Today');
        } else if ($date == $yesterday) {
			$date = Agora::lang('Yesterday');
		}
        return $date.' '.$time;
    }

	function _intl($date, $timestamp) {
		if(strpos($date, '{M}') !== false) {
			$date = str_replace('{M}', JDate::_monthToString(date('n', $timestamp), true), $date);
		}
		if(strpos($date, '{F}') !== false) {
			$date = str_replace('{F}', JDate::_monthToString(date('n', $timestamp)), $date);
		}
		if(strpos($date, '{D}') !== false) {
			$date = str_replace('{D}', JDate::_dayToString(date('w', $timestamp), true), $date);
		}
		if(strpos($date, '{l') !== false) {
			$date = str_replace('{l}', JDate::_dayToString(date('w', $timestamp)), $date);
		}
		return $date;
	}

        /*function _compile_lang(& $key)
        {
            return addslashes($this->lang->_(trim($key[1]),false));
        }*/

    function translate(& $tpl_source, & $smarty) {
        return
        preg_replace_callback('/##(.+?)##/', array('Agora','lang'), $tpl_source);

    }

    function bbcode($params,$content, & $smarty, $repeat)
    {
        if ($content) return $content;
    }

        /*function lang($params,$content, & $smarty, $repeat)
        {
            if ($content) return $content;
        }*/

    function agoraScriptDef($params,$content, & $smarty, $repeat)
    {
        if ($content !== NULL && strlen(trim($content)) > 0) {

            //			var_dump($doc);
            //			return $content;
            $this->doc->addScriptDeclaration($content, isset($params['type']) ? $params['type'] : 'text/javascript');
        }
    }

    function agoraScript($params,& $smarty)
    {
        if (!isset($params['src'])) {
            $smarty->trigger_error('src parameter not defined in {script} function');
            return;
        }
        $src = $params['src'];

        if (strpos($src,'http') === false) {
            $src = JURI::base() . 'components/com_agora/' . $src;
        }

        $type = isset($params['type'])		? $params['type']	: 'text/javascript';

        $doc = & JFactory::getDocument();
        $doc->addScript($src, $type);
    }

    function agoraFeed($params,& $smarty)
    {
            /*if (!isset($params['link'])) {
                $smarty->trigger_error("link parameter not defined in {feed} function");
                return;
            }*/

        $doc = & JFactory::getDocument();

        $rss = $params + array('format'=>'feed','type'=>'rss');
        $atom = $params + array('format'=>'feed','type'=>'atom');
		
        $attribs = array('type' => 'application/rss+xml', 'title' => 'RSS 2.0');
        $doc->addHeadLink(Agora::makeURL($rss), 'alternate', 'rel', $attribs);

        $attribs = array('type' => 'application/atom+xml', 'title' => 'Atom 1.0');
        $doc->addHeadLink(Agora::makeURL($atom), 'alternate', 'rel', $attribs);
    }

    function agoraStyle($params,& $smarty)
    {
        if (!isset($params['href'])) {
            $smarty->trigger_error("href parameter not defined in {style} function");
            return;
        }
        $type = isset($params['type'])		? $params['type']	: 'text/css';
        $media = isset($params['media'])	? $params['media']	: null;

        $doc = & JFactory::getDocument();
        $doc->addStyleSheet(Agora::getRoot() . $params['href'],$type, $media);
    }

    function agoraURL($params,& $smarty)
    {
        foreach ($params as $key=>$value)
        {
            if ($value === '#') {
				$value = Agora::getVar($key);
                $params[$key] = $value;
			}

			if (is_null($value) || empty($value)) {
				unset($params[$key]);
			}
        }

        if (is_array($params)) return Agora::makeURL($params, false);
        preg_match_all('/(\S+)=(\S+)/',$params,$match,PREG_PATTERN_ORDER);
        $parsed = array();
        foreach($match[1] as $key=>$value)
        {
            $param = $match[2][$key];
            if ($param === '#') {
                $param = Agora::getVar($key);
                if (is_null($param) || empty($param)) continue;
            }

            $parsed[$value] = $param;
        }

        return Agora::makeURL($parsed, false);
    }

    function agoraRoot($params,& $smarty)
    {
        if (is_array($params) && isset($params['tail'])) {
            return $this->root_url . $params['tail'];
        }

        return $this->root_url;
    }
    

    function fetchTemplate($template)
    {
        return $this->smarty->fetch($template);
    }

    function display($template = NULL)
    {	
		$document =& JFactory::getDocument();
		$document->addScriptDeclaration('var SITE_ROOT = \''. JURI::base(true) . '/\';' . "\n");
		
        if (Agora::getVar('type') === 'clean') {
            JRequest::setVar('tmpl', 'component'); //force the component template
            if ($this->template) {
                $template = $this->template;
            }
            $this->smarty->display("agora:$template.tpl");
            return;
        } elseif (Agora::getVar('type') === 'raw') {
            // this is a raw output - image or ajax or so. We don't need to display anything
            JRequest::setVar('format', 'raw'); //force the raw format
            if ($this->template) {
                $template = $this->template;
            }
            $this->smarty->display("agora:$template.tpl");
            return;
        } elseif (Agora::getVar('format') === 'raw') {
            // this is a raw output - image or ajax or so. We don't need to display anything
            JRequest::setVar('format', 'raw'); //force the raw format
            if ($this->template) {
                $template = $this->template;
            }
            $this->smarty->display("agora:$template.tpl");
            return;
        }
        $this->smarty->display('agora:header.tpl');

        if ($this->template)
        $this->smarty->display('agora:'.$this->template.'.tpl');
        elseif ($template)
        $this->smarty->display('agora:'.$template.'.tpl');

        $this->smarty->display('agora:footer.tpl');
		
		if (isset($_SESSION['add_attachment'])) {
			unset($_SESSION['add_attachment']);
		}
    }
}
